# Class for message translation
=begin
Copyright (C) 2014 Enrique Rando

This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.

http://www.gnu.org/licenses/gpl-2.0.html
=end



class Translator 
	# Object creation
	# Parameter	file	The file with the translation table
	def initialize(file)
		load_table(file) 
	end
	
	# Load a translation table from file
	# Parameters
	#	file	The file with the translation table
	#	add		If false, internal translation table will be deleted before loading the file
	def load_table(file, add = false)
		# Delete table if needed
		@table = {} unless add
	
		# Read the file and process its lines
		File.read(file).lines.each_with_index do |x, i|
			# Remove extra blanks
			line = x.strip
			
			# Skip empty lines and comments
			next if line.empty? or line.match(/^\s*#/)
			
			# Extract data
			match = line.match(/^\s*(?<token>\w+):(?<translation>.*)$/)
			raise "Syntax Error for language file #{file} at line #{i + 1}:\n   #{x}" if match.nil?
			
			# Insert data into table
			@table[match[:token].to_sym] = match[:translation]
		end
	end
	
	# Translate an input using a set of token=>value
	# Parameters
	# 	input	The input string or symbol
	#	tokens	Hash with the token=>value pairs
	def translate(input, tokens={})
		# Lookup input in translation table if it is a symbol
		# If it is a string, prepare it for HTML output
		string = input.is_a?(Symbol) ? @table[input] : CGI.escapeHTML(input.to_s)
		return nil if string.nil?
		
		# Loop until no tags are left in the input
		while true		
			match = string.match(/\[\[(?<token>[^\]]+)\]\]/)
			break if match.nil?
			
			# Replace tokens with the information provided by "tokens" parameter or the translation table as needed
			token = match[:token].to_sym
			with = tokens.has_key?(token) ? CGI.escapeHTML(tokens[token].to_s) : translate(token, tokens)
			with = "" if with.nil?
			string = string.gsub("[[#{token}]]", with.to_s) 
		end

		# And that's all...
		return string
	end
end
